<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"
    />
    <title>上传图片用例</title>
    <link
      rel="stylesheet"
      href="http://cdn.suoluomei.com/common/js/css/wpf/weui.css"
    />
    <link
      rel="stylesheet"
      href="http://cdn.suoluomei.com/common/js/css/wpf/jquery-weui.css"
    />
    <link
      rel="stylesheet"
      href="http://hfc.suoluomei.com/hpl/Public/common/css/photoswipe.css"
    />

    <style>
      * {
        padding: 0;
        margin: 0;
      }
      body {
        -webkit-tap-highlight-color: transparent;
      }
      .wpf_orderBox {
        position: relative;
        overflow-x: hidden;
        width: 100%;
      }
      .weui-cells,
      .weui-panel {
        margin-top: 0;
      }
      .weui-uploader__info {
        font-size: 14px;
      }
      .weui-gallery {
        display: none;
      }
      .weui-icon-delete {
        padding-left: 10px;
        box-sizing: border-box;
      }
      .weui-icon-close {
        padding-right: 10px;
        box-sizing: border-box;
      }
      .weui-icon-close:before {
        background-image: url(http://sucai.suoluomei.cn/sucai_zs/images/20190313094228-close.svg);
        width: 22px;
        height: 22px;
        background-size: 100% 100%;
        content: '';
      }

      .refresh_btn {
        width: 30%;
        height: 38px;
        line-height: 38px;
        margin: 30px auto 0;
        background: #1aad19;
        letter-spacing: 2px;
        color: #ffffff;
        font-size: 16px;
      }

      .weui-cell_access {
        -webkit-tap-highlight-color: transparent;
      }
      .weui_loading {
        left: calc(50% - 19px);
        top: calc(50% - 19px);
      }
      .input-picker {
        border: 0;
        outline: 0;
        font-size: 16px;
        line-height: 1em;
        text-align: right;
        padding-right: 10px;
        color: #8d8d8d;
        -webkit-tap-highlight-color: transparent;
        background: transparent;
      }
    </style>
  </head>
  <body>
    <div class="wpf_orderBox">
      <div class="weui-cells">
        <div id="label" class="weui-cell weui-cell_access" href="javascript:;">
          <div class="weui-cell__bd">
            <p>请选择标签</p>
          </div>
          <div class="weui-cell__ft">
            <input class="input-picker" type="text" id="labelPicker" readonly />
          </div>
        </div>
      </div>
      <div class="weui-cells weui-cells_form">
        <div class="weui-cell">
          <div class="weui-cell__bd">
            <div class="weui-uploader">
              <div class="weui-uploader__hd">
                <p class="weui-uploader__title">请上传图片</p>
                <div class="weui-uploader__info">提示：(最多上传9张)</div>
              </div>
              <div class="weui-uploader__bd">
                <ul class="weui-uploader__files" id="uploaderFiles"></ul>
                <div class="weui-uploader__input-box">
                  <input
                    id="uploaderInput"
                    class="weui-uploader__input"
                    type="file"
                    accept="image/*"
                    multiple="multiple"
                    onchange="uploadImg(event)"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="weui-cells">
        <div id="showTime" class="weui-cell weui-cell_access">
          <div class="weui-cell__bd">
            <p>
              发布时间
            </p>
          </div>
          <div class="weui-cell__ft">
            <input class="input-picker" type="text" id="timePicker" readonly />
          </div>
        </div>
      </div>
      <!--点击图片放大-->
      <div class="weui-gallery"></div>
      <a href="javascript:;" class="weui-btn refresh_btn">提交</a>
    </div>
  </body>
</html>
<script src="http://cdn.suoluomei.com/common/js/jquery-2.1.4.min.js"></script>
<script src="http://cdn.suoluomei.com/common/js/jquery-weui.js"></script>
<script src="http://cdn.suoluomei.com/common/js2.0/city-picker/city-picker.min.js"></script>
<script src="http://hfc.suoluomei.com/hpl/Public/common/js/photoswipe.js"></script>

<!-- <script src="https://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/vconsole/2.5.1/vconsole.min.js"></script> -->
<script>
  var apiList = {
    uploadFile:
      'http://ydnshop.hepulanerp.com/sucai_t/public/index.php/post/post/uploadFile',
    label:
      'http://ydnshop.hepulanerp.com/train/public/index.php/api/Mobile/getLabel',
    submit:
      'http://ydnshop.hepulanerp.com/train/public/index.php/api/mobile/setImgScore'
  }
  var defaultParam = {
    uploadKey: 'Gn1xVdBiTClSSHKZifg0pTQSU5XGagWO',
    apiKey: 'yzI2dPfhwI3I6yG^w2i*Oh3targlBaP*'
  }
  var URL = window.URL || window.webkitURL || window.mozURL
  var labels = []
  var perid = '{$perid}'
  var id = 0
  var fileinfo = []
  var thumbImgArr = []
  var $labelPicker = $('#labelPicker')
  var $timePicker = $('#timePicker')

  function uploadImg(e) {
    var files = e.target.files || e.dataTransfer.files
    var imgArr = []
    var sum = files.length + fileinfo.length

    if (sum > 9) {
      $.toast('图片最多上传9张', 'text')
      return
    }

    for (var i = 0; i < files.length; i++) {
      ;(function(file) {
        if (!/^image/.test(file.type)) {
          $.alert('', '必须上传图片')
          return
        }

        var reader = new FileReader()
        var formData = new FormData()

        reader.onload = function() {
          formData.append('key', defaultParam.uploadKey)
          formData.append('file', file)

          thumbImgArr.push(URL.createObjectURL(file))

          renderUploadImgDom(file)
          $.showLoading()
          ajaxPostFile(formData, function(data) {
            fileinfo.push(data.info)
            $.hideLoading()
          })
        }
        reader.readAsBinaryString(file)
      })(files[i])
    }
    e.target.value = ''
  }

  function renderUploadImgDom(file) {
    $('#uploaderFiles').append(
      '<li class="weui-uploader__file" id="' +
        id +
        '" data-id="' +
        id +
        '" style="background-image:url(' +
        URL.createObjectURL(file) +
        ')"></li>'
    )
    id++
  }
  function ajaxPostFile(formData, cb) {
    $.ajax({
      type: 'POST',
      url: apiList.uploadFile,
      processData: false,
      contentType: false,
      data: formData,
      dataType: 'json',
      success: function(resp) {
        cb(resp)
      }
    })
  }

  $(document).ready(function() {
    // 点击图片放大
    $(document).on('touchstart', '.weui-uploader__file', function() {
      var i = $(this).data('id')
      var myli =
        '<div class="weui-gallery_box">' +
        '<span class="weui-gallery__img" style="background-image: url(' +
        fileinfo[i].url +
        ');"></span>' +
        '<div class="weui-gallery__opr">' +
        '    <a href="javascript:" class="weui-gallery__del">' +
        '        <i class="weui-icon-close weui-icon_gallery-close gallery-close"></i>' +
        '        <i class="weui-icon-delete weui-icon_gallery-delete" data-index="' +
        i +
        '"></i>' +
        '    </a>' +
        '</div>' +
        '        </div>'
      $('.weui-gallery').append(myli)
      $('.weui-gallery').fadeIn(600)
    })

    // 点击关闭按钮
    $(document).on('click', '.gallery-close', function() {
      $('.weui-gallery_box').remove()
      $('.weui-gallery').fadeOut(600)
    })

    // 删除图片
    $(document).on('click', '.weui-icon-delete', function() {
      var i = $(this).data('index')
      fileinfo.splice(i, 1)
      $('#' + i).remove()
      $('[data-index]').each(function(index, item) {
        $(item).attr('data-index', index)
      })
      $('[data-id]').each(function(index, item) {
        $(item).attr('data-id', index)
        $(item).attr('id', index)
      })
      id = fileinfo.length
      $('.weui-gallery_box').remove()
      $('.weui-gallery').fadeOut(600)
      $('.weui-uploader__input-box').css('display', 'block')
    })

    function initLabelPicker(labels) {
      // TODO: 文本匹配对应id传给后台
      $labelPicker.picker({
        title: '选择标签',
        cols: [
          {
            textAlign: 'center',
            values: labels || []
          }
        ]
      })
    }

    $timePicker.calendar()
    $labelPicker.height($labelPicker.parent().height())
    $timePicker.height($timePicker.parent().height())
    $labelPicker.one('click', function() {
      fetchLabels(function(res) {
        console.log('TCL: res', res)
        var tmp = []

        for (var i = 0, l = res.length; i < l; i++) {
          tmp.push(res[i]['name'])
        }

        initLabelPicker(tmp)
        console.log('TCL: tmp', tmp)
        $labelPicker.trigger('click')
      })
    })
    $labelPicker.on('focus', function() {
      document.activeElement.blur() //屏蔽默认键盘弹出；
    })
    /**
     * @description: 获取标签
     * @param {type}
     * @return:
     */
    function fetchLabels(cb) {
      $.ajax({
        type: 'POST',
        url: apiList.label,
        data: {
          api_key: defaultParam.apiKey
        },
        dataType: 'json',
        success: function success(resp) {
          if (resp.errcode == 0) {
            labels = resp.data.children
            console.log('TCL: fetchLabels -> labels', labels)
            cb(resp.data.children)
          } else {
            $.alert(resp.msg)
          }
        }
      })
    } // 提交获取数据

    $('.refresh_btn').click(function() {
      var tmpLabel = labels.filter(function(item) {
        return item.name == $labelPicker.val()
      })
      var tmpLabelId = tmpLabel.length > 0 && [tmpLabel[0]['id']]
      var uploadTime = $timePicker.val()
      // TODO: 校验提交数据
      console.log('TCL: tmpLabelId', tmpLabelId)
      if (fileinfo == '') {
        $.toptip('请上传图片')
        return
      } else if (tmpLabelId == '') {
        $.toptip('请选择标签')
        return
      }
      nowTime = new Date()
      if (uploadTime == '') {
        uploadTime =
          nowTime.getFullYear() +
          '/' +
          (nowTime.getMonth() + 1) +
          '/' +
          nowTime.getDate()
      }
      console.log('TCL: tmpLabel', tmpLabel)
      $.showLoading()
      $.ajax({
        type: 'POST',
        url: apiList.submit,
        data: {
          perid: perid,
          api_key: defaultParam.apiKey,
          file: fileinfo,
          label: tmpLabelId,
          upload_time: uploadTime
        },
        dataType: 'json',
        success: function success(res) {
          if (res.status == 1) {
            $.hideLoading()
            $.toast(
              res.msg,
              'text',
              function() {
                window.location.href = '__CONTROLLER__/imgList'
              },
              800
              )
          } else {
            $.alert(res.msg)
          }
        }
      })
    })
  })
</script>
